import React from 'react';
import {globalStore} from "../libs/ShareStore";
import ANavigationComponent, {ANavigationComponentProp} from "../components/navigator/ANavigationComponent";
import ChatListData from "../model/item/ChatListData";
import {
    FlatList,
    Image,
    NativeSyntheticEvent,
    NativeTouchEvent,
    Platform,
    StyleSheet,
    TouchableOpacity,
    View
} from "react-native";
import ChatListItem from "../components/listview/item/ChatListItem";
import {FileInfo} from "../libs/sdk/echatim/core/fileclient/FileServerClient";
import Toast from "../components/toast/Toast";
import {ChatsStore} from "../model/store/ChatsContentStore";
import EChatIMApis from "../libs/sdk/echatim/core/apis/EChatIMApis";
import MessageSendForm from "../libs/sdk/echatim/model/form/MessageSendForm";
import Beans from "../libs/sdk/echatim/common/utils";
import HistoryListForm from "../libs/sdk/echatim/model/form/HistoryListForm";
import {ScreenDimensions} from "../libs/utils/ScreenDimensions";
import MessageInputComponent from "../components/chatwin/MessageInputComponent";
import ENavigationButton, {ENavigationButtonProp, ENavigationButtonState} from "../components/utils/ENavigationButton";
import {NavigationScreenProp} from "react-navigation";
import NavigatorBar from "../components/navigator/NavigatorFactory";
import {SimpleDateFormat} from "../libs/utils/SimpleDateFormat";
import {Resource} from "../resource/Resource";

type ChatWinPageProps = {
    // category:string
} & ANavigationComponentProp

type ChatWinPageStateType = {
    chats:Array<ChatListData>,
    // msgContentText:string, // 输入框的
    refreshing:boolean,
    height:number|undefined
}

export class ChatRightNavigationBtn extends ENavigationButton<ENavigationButtonProp, ENavigationButtonState>{
    protected onPress(ev: NativeSyntheticEvent<NativeTouchEvent>, navigation: NavigationScreenProp<any, any>) {
        const selectId:any = this.getRelationPageParams().auid;
        console.log(`onPress:params:` + this.getRelationPageParams().select);
        switch (this.getRelationPageParams().select) {
            case 'friend' :
            case 'session':
                EChatIMApis.userGet.call({auid:selectId})
                    .then((resp)=>{
                    NavigatorBar.push('ModifyFriendInfoPage', {info:resp.data});
                }).catch((e)=>{
                    Toast.show(`无法获取用户信息:error:${e}`)
                });
                break;
            case 'room':
                EChatIMApis.getRoom.call({rid:parseInt(selectId)})
                    .then((resp)=>{
                        NavigatorBar.push('ModifyRoomInfoPage', {info:resp.data});
                    }).catch((e)=>{
                    Toast.show(`无法获取讨论组信息:error:${e}`)
                });
                break;
        }
        super.onPress(ev, navigation);
    }

    render() {
        if(globalStore.chatsContent.select === 'friend' || globalStore.chatsContent.select === 'room'){
            return (
                <TouchableOpacity activeOpacity={1} onPress={(e) => this.onPress(e, this.props.navigation)}>
                    <Image style={{width: 16, height: 16, marginRight:12}}  source={Resource.align} />
                </TouchableOpacity>
            );
        }
        // session 点进来时暂不显示
        else {
            return (
                <View />
            );
        }
    }
}

export default class ChatWinPage  extends ANavigationComponent<ChatWinPageProps, ChatWinPageStateType>  {
    private chatList:FlatList|any;
    private messageInput:MessageInputComponent|any;
    private originWindowHeight:number|any;

    constructor(props:ChatWinPageProps) {
        super(props);
        console.log(`select chat windows:${globalStore.chatsContent.select} chatTo:${globalStore.chatsContent.selectId}`);
        this.originWindowHeight = ScreenDimensions.screen.height - ScreenDimensions.navigationBar.height;
        this.state = {
            chats:new Array<ChatListData>(),
            // msgContentText:'',
            refreshing: false,
            height: Platform.OS === 'web' ? (this.originWindowHeight-56) : undefined
        };
        globalStore.addChatListener(this.onChatsUpdate.bind(this));
        this.getNavigationParams().auid = globalStore.chatsContent.selectId;
        this.getNavigationParams().select = globalStore.chatsContent.select;
    }

    public caller(){
        console.log(`caller`);
    }

    componentDidMount(): void {
        globalStore.chatsContent.chats = [];
        console.log("chat to user:" + globalStore.chatsContent.friendInfo.auid);
        // 获取自己跟 好友/群 的聊天记录
        const historyListForm = new HistoryListForm();
        historyListForm.fromUser = globalStore.userInfo.auid;
        historyListForm.toTarget = globalStore.isSelectPersonTag() ? globalStore.chatsContent.friendInfo.auid : globalStore.chatsContent.roomInfo.rid + '';
        historyListForm.way =  globalStore.isSelectPersonTag() ? 'P2P' : 'P2R';
        historyListForm.startTimestamp = 0;
        historyListForm.endTimestamp = new Date().getTime();
        historyListForm.limit = 12;

        EChatIMApis.historyListMessage.call(historyListForm).then((resp) => {
            const msgs = resp.data.reverse();
            globalStore.chatsContent.chats = msgs;
            globalStore.notifyChatUpdate();
        }).catch((e) => {
            globalStore.showApiErrorToast(e);
        })
    }

    onChatsUpdate(chats:Array<ChatsStore>):void{
        this.setState( {
            chats:chats.map((v)=>{
                return Beans.to(v);
            }),
            refreshing: !this.state.refreshing
        }, function () {
            // self.chatList.scrollToEnd();
        });

    }



    getFlatListRef = (chatList) => {
        this.chatList = chatList;
        return chatList;
    };


    sendMessage(type, jsonBody) {
        const way = (globalStore.chatsContent.select=='friend' || globalStore.chatsContent.select=='session') ? 'P2P' : 'P2R';
        if (way === 'P2P' || way === 'P2R') {
            const form = new MessageSendForm();
            form.fromUser = globalStore.userInfo.auid;
            form.toTarget = way === 'P2P' ? globalStore.chatsContent.friendInfo.auid : globalStore.chatsContent.roomInfo.rid + '';
            form.way = way;
            form.type = type;
            form.body = jsonBody;
            EChatIMApis.sendMessage.call(form).then((resp) => {
                // 加入刚刚发的信息到聊天窗口
                const chat = new ChatsStore();
                chat.toMe = 0;
                chat.type = type;
                chat.way = way;
                chat.body = jsonBody;
                chat.createTime = SimpleDateFormat.format(new Date(), 'yyyy-MM-dd hh:mm:ss');
                globalStore.chatsContent.chats.push(chat);
                // 清空聊天发送框
                // globalStore.msgContent.text = '';
                this.messageInput.clearInput();
                // notify update
                globalStore.notifyChatUpdate();

                Toast.show("发送成功");
                // globalStore.scrollMessageContainerToBottom();
            }).catch((e) => {
                globalStore.showApiErrorToast(e);
            })
        }
    }

    onFileStartUpload(fileInfo:FileInfo){
        const prevState = this.state;

        const data = new ChatListData();
        data.name = fileInfo.name;
        data.toMe = 0;
        data.type = fileInfo.type ? fileInfo.type : 'FILE';
        data.way = globalStore.isSelectPersonTag() ? 'P2P' : 'P2R';
        data.body = {size:fileInfo.size, name:fileInfo.name, body:''};
        data.fileIdUploading = fileInfo.id; // 文件在上传中
        prevState.chats.push(data);
        this.setState(prevState);

    }

    onFileUploaded(fileInfo:FileInfo){
        this.sendMessage(fileInfo.type ? fileInfo.type : 'FILE', {
            body:fileInfo.url,
            name:fileInfo.originFileName,
            size:fileInfo.size
        });
    }


    onAdjustWebLayout(height:number){
        if(Platform.OS !== 'web'){
            return;
        }
        const prevState = this.state;
        this.setState({
            chats: prevState.chats,
            refreshing: prevState.refreshing,
            height: Platform.OS === 'web' ? (this.originWindowHeight - height) : undefined,
        })
    }


    getMessageComponent = (messageInput) => {
        this.messageInput = messageInput;
        return messageInput;
    };

    render() {
        return (
            <View style={{flex:1}}>
                <View style = {[chatWindowStyles.container,{height:this.state.height}]}>
                    <View style={chatWindowStyles.list}>
                        <FlatList
                            extraData = {this.state.refreshing}
                            data = {this.state.chats}
                            keyExtractor = {(item,index)=>item.createTime+index}
                            ref={this.getFlatListRef}
                            onContentSizeChange={()=> this.chatList!.scrollToEnd()}
                            renderItem = {({item})=><ChatListItem data={item} avatar={item.avatar} name={item.name}  body={item.body.body}  createTime={item.createTime} toMe={item.toMe}/>}
                        />
                    </View>
                </View>

                <MessageInputComponent ref={this.getMessageComponent}
                    onSendMessage={(msgType,jsonBody)=>{this.sendMessage(msgType, jsonBody)}}
                    onFileStartUpload={(file:FileInfo)=>{this.onFileStartUpload(file)}}
                    onFileUploaded={(file:FileInfo)=>{this.onFileUploaded(file)}}
                    onAdjustLayout={(height)=>{this.onAdjustWebLayout(height)}}
                />

            </View>
        );
    }
}

export const chatWindowStyles = StyleSheet.create({
    actionBtn: {
        flex: 1,
        backgroundColor: '#F5FCFF',
    },
    list: {
        flex: 1,
        paddingTop: 22
    },

    container: {
        flexDirection:'column',
        flex:1,
        paddingLeft: 14,
        paddingRight: 14,
        backgroundColor:'#EAEDF6'
    },

    content: {
        flexDirection:'column',
        justifyContent:'space-around',
        marginLeft:6,
        flexShrink: 1,
        flex:1
    },


});

